package cn.edu.upc.letao.service;

import cn.edu.upc.letao.dao.CommonMemberDao;
import cn.edu.upc.letao.entity.CommonMember;
import cn.edu.upc.letao.util.MailUtil;
import cn.edu.upc.letao.util.MyTimeTransfer;
import cn.edu.upc.letao.util.RandomCharUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * Created by cheney on 2017/4/5.
 */
@Service
public class LoginService {
    @Autowired
    private AuthService authService;
    @Autowired
    private CommonMemberDao commonMemberDao;
    @Autowired
    private HttpSession httpSession;
    @Autowired
    private LoginRecordService loginRecordService;
    @Autowired
    private GoldService goldService;
    @Autowired
    private MemberService memberService;

    public boolean login(String email,String password){
        if (email != null && password != null) {
            List<CommonMember> userses = commonMemberDao.findByEmail(email);
            if( !userses.isEmpty()){
                //非空，找到此用户
                BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

                if(passwordEncoder.matches(password, userses.get(0).getPassword())){
                    //登录成功
                    CommonMember thisUsers = userses.get(0);

                    //增加每日登录的金币
                    thisUsers = goldService.addLoignGold(thisUsers);
                    //金币改变了 所以保存一下用户
                    memberService.saveUserAndGroupid(thisUsers);


                    //保存登录记录
                    Date thisTime = new Date(MyTimeTransfer.getCurrentTimeStamp());
                    String thisToken = RandomCharUtil.getRandomNumberUpperLetterChar(16);//厉害了！！！！！！！！！！！！！！！！！！！

                    //记录登录记录
                    loginRecordService.addLoginRecord(thisUsers.getUid(), thisToken);

                    //设置session
                    httpSession.setAttribute("visit_time", thisTime.getTime());
                    httpSession.setAttribute("visit_token", thisToken);
                    httpSession.setAttribute("visit_user_name", thisUsers.getEmail());
                    httpSession.setAttribute("visit_user_id",thisUsers.getUid());
                    httpSession.setMaxInactiveInterval(1200);//20分钟不活动则会话失效
                    System.out.println("in isAuthenticated user id:"+httpSession.getAttribute("visit_user_id"));
                    return true;
                }else{
                    //顺便把session失效
                    httpSession.invalidate();
                }
            }else{
                //顺便把session失效
                httpSession.invalidate();
            }
        }
        return false;
    }

    public boolean adminLogin(String credit,String password){
        if (credit != null && password != null) {
            List<CommonMember> userses = commonMemberDao.findOneAdmin(credit);
            if( !userses.isEmpty()){
                //非空，找到此用户
                BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

                if(passwordEncoder.matches(password, userses.get(0).getPassword())){
                    //登录成功
                    CommonMember thisUsers = userses.get(0);

                    //保存登录记录
                    Date thisTime = new Date(MyTimeTransfer.getCurrentTimeStamp());
                    String thisToken = RandomCharUtil.getRandomNumberUpperLetterChar(16);//厉害了！！！！！！！！！！！！！！！！！！！

                    //记录登录记录
                    loginRecordService.addLoginRecord(thisUsers.getUid(), thisToken);

                    //设置session
                    httpSession.setAttribute("admin_visit_time", thisTime.getTime());
                    httpSession.setAttribute("admin_visit_token", thisToken);
                    httpSession.setAttribute("admin_visit_user_name", thisUsers.getEmail());
                    httpSession.setAttribute("admin_visit_user_id",thisUsers.getUid());
                    httpSession.setMaxInactiveInterval(1200);//20分钟不活动则会话失效
                    System.out.println("in isAuthenticated user id:"+httpSession.getAttribute("admin_visit_user_id"));
                    return true;
                }else{
                    //顺便把session失效
                    httpSession.invalidate();
                }
            }else{
                //顺便把session失效
                httpSession.invalidate();
            }
        }
        return false;
    }

    public boolean register(String email,String password) {
        if (email != null && password != null) {
                BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

                CommonMember users = new CommonMember(email, passwordEncoder.encode(password));

                MailUtil mailUtil = new MailUtil();
                mailUtil.send(email,"尊敬的"+email+":</br>" +
                        "感谢您注册乐淘，请发表言论时遵守当地的法律法规。");

                commonMemberDao.save(users);
                return this.login(email, password);//直接登录
        }

        return false;
    }
}
